{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b050edae-48cf-47ba-b2ae-bf9fc9098bb4",
   "metadata": {},
   "source": [
    "## Synonym Replacement for Text Augmentation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0ab61d1f-466f-4469-99da-b172a959c2cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Author: Sebastian Raschka\n",
      "\n",
      "Python implementation: CPython\n",
      "Python version       : 3.10.6\n",
      "IPython version      : 8.12.0\n",
      "\n",
      "nltk: 3.8.1\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%load_ext watermark\n",
    "%watermark -a 'Sebastian Raschka' -v -p nltk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2e4539cb-2c81-47e2-8be9-03206f750771",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package wordnet to\n",
      "[nltk_data]     /Users/sebastian/nltk_data...\n",
      "[nltk_data]   Package wordnet is already up-to-date!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import nltk\n",
    "\n",
    "nltk.download('wordnet')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "81874f62-821b-40b3-94a0-f22e45d82352",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package wordnet to\n",
      "[nltk_data]     /Users/sebastian/nltk_data...\n",
      "[nltk_data]   Package wordnet is already up-to-date!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['quickly',\n",
       " 'rapidly',\n",
       " 'speedily',\n",
       " 'chop-chop',\n",
       " 'apace',\n",
       " 'promptly',\n",
       " 'quickly',\n",
       " 'quick',\n",
       " 'cursorily',\n",
       " 'quickly']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from nltk.corpus import wordnet\n",
    "\n",
    "nltk.download('wordnet')\n",
    "\n",
    "def get_synonyms(word):\n",
    "    synonyms = []\n",
    "    for syn in wordnet.synsets(word):\n",
    "        for lemma in syn.lemmas():\n",
    "            synonyms.append(lemma.name())\n",
    "    return synonyms\n",
    "\n",
    "\n",
    "get_synonyms(\"quickly\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6987216a-2485-4494-8d0f-45f5feffe5dd",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package averaged_perceptron_tagger to\n",
      "[nltk_data]     /Users/sebastian/nltk_data...\n",
      "[nltk_data]   Package averaged_perceptron_tagger is already up-to-\n",
      "[nltk_data]       date!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# for part of speech tagging\n",
    "nltk.download('averaged_perceptron_tagger')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "85d75f89-11dd-4248-b005-4c08981aa79b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('The', 'DT'),\n",
       " ('cat', 'NN'),\n",
       " ('quickly', 'RB'),\n",
       " ('jumped', 'VBD'),\n",
       " ('over', 'IN'),\n",
       " ('the', 'DT'),\n",
       " ('lazy', 'JJ'),\n",
       " ('dog', 'NN'),\n",
       " ('.', '.')]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def get_position_tags(text):\n",
    "    words = nltk.word_tokenize(text)\n",
    "    pos_tags = nltk.pos_tag(words)\n",
    "    return pos_tags\n",
    "    \n",
    "get_position_tags(\"The cat quickly jumped over the lazy dog.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c4fb3228-320a-4722-bbb5-d9c8098c10b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nltk\n",
    "from nltk.corpus import wordnet\n",
    "import random\n",
    "\n",
    "random.seed(123)\n",
    "\n",
    "\n",
    "def synonym_replacement(text, num_replacement=2):\n",
    "\n",
    "    words = nltk.word_tokenize(text)\n",
    "    \n",
    "    # tag nounds, adjectives, etc.\n",
    "    pos_tags = nltk.pos_tag(words)\n",
    "    \n",
    "    # Only replace adverbs (RB) and adjectives (JJ) for simplicity here\n",
    "    candidates = [word for word, pos in pos_tags if pos in ['RB', 'JJ']]\n",
    "\n",
    "    if len(candidates) < num_replacement:\n",
    "        return words\n",
    "    \n",
    "    # Randomly choose the words to be replaced\n",
    "    words_to_replace = random.sample(candidates, num_replacement)\n",
    "    \n",
    "    \n",
    "    # For each word to replace, we get its synonyms and choose one randomly\n",
    "    for word in words_to_replace:\n",
    "        synonyms = get_synonyms(word)\n",
    "        if synonyms:\n",
    "            synonym = random.choice(synonyms)\n",
    "            text = text.replace(word, synonym, 1)\n",
    "    \n",
    "    return text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "19267b15-9267-443b-a81d-fc0241eb737e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "The cat rapidly jumped over the work-shy dog.\n"
     ]
    }
   ],
   "source": [
    "text = \"\"\"\n",
    "The cat quickly jumped over the lazy dog.\n",
    "\"\"\"\n",
    "\n",
    "sentences = nltk.sent_tokenize(text)\n",
    "augmented_sentences = [synonym_replacement(sentence) for sentence in sentences]\n",
    "augmented_paragraph = ' '.join(augmented_sentences)\n",
    "\n",
    "print(augmented_paragraph)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e107faa-8b4c-43c2-82eb-e2d9d82eab05",
   "metadata": {},
   "source": [
    "**Compare original with augmented text**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a8773c0b-2f11-42bc-b03e-ed850b1ae9bf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  The\n",
      "  cat\n",
      "- quickly\n",
      "+ rapidly\n",
      "  jumped\n",
      "  over\n",
      "  the\n",
      "- lazy\n",
      "+ work-shy\n",
      "  dog.\n"
     ]
    }
   ],
   "source": [
    "import difflib\n",
    "\n",
    "\n",
    "d = difflib.Differ()\n",
    "diff = d.compare(text.split(), augmented_paragraph.split())\n",
    "\n",
    "print('\\n'.join(diff))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
